package com.zmx.job.admin.utils;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Description: 随机选取元素工具类
 * @ClassName: RandomElementUtils
 * @Author zhaomxr
 * @Date 2021-12-22 14:18
 */
public class RandomElementUtils {

    private static ThreadLocalRandom getRandom() {
        return ThreadLocalRandom.current();
    }

    /**
     * 随机数范围 0-max 包含0不包含max
     *
     * @param max
     * @return
     */
    private static int getRandomInt(int max) {
        return getRandom().nextInt(max);
    }

    /**
     * list中随机取值
     * @param list
     * @return
     */
    public static Object getRandomList(List list) {
        return list.get(getRandomInt(list.size()));
    }

    /**
     * Set中随机取值
     * @param set
     * @return
     */
    public static Object getRandomSet(Set set) {
        int randomInt = getRandomInt(set.size());
        int number = 0;

        for (Object obj : set) {
            if (randomInt == number) {
                return obj;
            }
            number++;
        }
        return set.iterator().next();
    }
}
